package com.xz.supplierOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.diagnosisOrder.domain.DiagnosisTreatmentOrder;
import com.xz.diagnosisOrder.dto.DiagnosisTreatmentOrderSaveDto;
import com.xz.purchase.domain.Purchase;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.mapper.PurchaseMapper;
import com.xz.purchase.mapper.PurchaseProductMapper;
import com.xz.purchase.service.IPurchaseProductService;
import com.xz.purchase.service.IPurchaseService;
import com.xz.repertory.domain.RepertoryFlow;
import com.xz.repertory.service.IRepertoryFlowService;
import com.xz.supplierOrder.domain.SupplierOrder;
import com.xz.supplierOrder.domain.SupplierOrderDetail;
import com.xz.supplierOrder.domain.SupplierOrderDetailRecord;
import com.xz.supplierOrder.enums.SupplierOrderStatusEnum;
import com.xz.supplierOrder.service.ISupplierOrderDetailRecordService;
import com.xz.supplierOrder.service.ISupplierOrderDetailService;
import com.xz.supplierOrder.service.ISupplierOrderProductService;
import com.xz.supplierOrder.service.ISupplierOrderService;
import com.xz.warehouse.domain.Warehouse;
import com.xz.warehouse.service.IWarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 贸易中间商订单Service业务层处理
 *
 * @author xz
 * @date 2024-02-27
 */
@Service
public class SupplierOrderProductServiceImpl implements ISupplierOrderProductService {
  @Resource
  private IPurchaseProductService purchaseProductService;
  @Resource
  private PurchaseProductMapper purchaseProductMapper;
  @Autowired
  private ISupplierOrderDetailRecordService supplierOrderDetailRecordService;
  @Autowired
  private ISupplierOrderService supplierOrderService;
  @Autowired
  private ISupplierOrderDetailService supplierOrderDetailService;
  @Autowired
  private IRepertoryFlowService repertoryFlowService;
  @Autowired
  private IWarehouseService iWarehouseService;
  @Autowired
  private PurchaseMapper purchaseMapper;
  @Autowired
  private IPurchaseService purchaseService;

  /**
   * 检索对应的采购商品明细
   *
   * @param detail （贸易中间商）单据商品
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public List<PurchaseProduct> getPurchaseProducts(SupplierOrderDetail detail) {
    //开始检索出对应的采购商品明细对象
    PurchaseProduct queryProductParam = new PurchaseProduct();
    queryProductParam.setProductName(detail.getProductName());
    queryProductParam.setProductParam(detail.getProductParam());
    queryProductParam.setWarehouseId(detail.getWarehouseId());
    queryProductParam.setBatchNumber(detail.getBatchNumber());
    queryProductParam.setBatchDate(detail.getBatchDate());
    queryProductParam.setValidity(detail.getValidity());
    queryProductParam.setSupplierId(detail.getSupplierId());
    List<PurchaseProduct> purchaseProductList = purchaseProductMapper.getListByParam(queryProductParam);
    return purchaseProductList;
  }

  /**
   * 查询可用库存数量
   *
   * @param detail （贸易中间商）单据商品
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int countPurchaseProducts(SupplierOrderDetail detail) {
    List<PurchaseProduct> purchaseProductList = getPurchaseProducts(detail);
    if (CollectionUtils.isEmpty(purchaseProductList)) {
      return 0;
    }
    int count = purchaseProductList.stream().mapToInt(PurchaseProduct::getAvailableStock).sum();
    return count;
  }

  /**
   * 发货--更新采购商品明细数量
   *
   * @param supplierOrder （贸易中间商）单据
   * @param details       （贸易中间商）单据商品
   * @param storageType   16.贸易中间商发货单（发货） 21.贸易中间商换货单（换货）
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deliverySupplierOrder(SupplierOrder supplierOrder, List<SupplierOrderDetail> details, int storageType) {

    // 库存流水记录 -- 作用是追踪库存流水的日志
    List<PurchaseProduct> purchaseProductFlows = new ArrayList<>();
    // 贸易中间商订单商品出入库记录 -- 该记录作用是用户进行冲红操作业务时，方便代码的处理。
    List<SupplierOrderDetailRecord> detailRecords = new ArrayList<>();

    List<RepertoryFlow> repertoryFlowList = new ArrayList<>();
    //开始发货操作（扣减库存 -- 采购商品明细的库存）
    details.forEach(detail -> {
      // 查询对应的采购商品明细
      List<PurchaseProduct> purchaseProductList = getPurchaseProducts(detail);
      // 校验商品库存是否充足
      String message = String.format("提交失败，商品[%s]",detail.getProductName());
      if (CollectionUtils.isEmpty(purchaseProductList)) {
        message =  message + "已售空或商品信息已更改，请选择其他商品。";
        throw new ServiceException(message);
      }
      int count = purchaseProductList.stream().mapToInt(PurchaseProduct::getAvailableStock).sum();
      if (detail.getProductNum() > count) {
        message = message + "库存发生变化，剩余库存为：" + count;
        throw new ServiceException(message);
      }

      // 扣减库存
      List<PurchaseProduct> purchaseProducts = repertoryFlowService.convertFlowData(purchaseProductList, detail.getProductNum(), supplierOrder.getOrderNo(), supplierOrder.getId());
      // 用detail中的合同价格填充，因为后续日志保存时，会取出该字段作为售价。
      purchaseProducts.forEach(data -> {
        //data.setMemberId(supplierOrder.getSupplierId());
        //data.setMemberName(supplierOrder.getSupplierName());
        data.setPrice(detail.getContractPrice());
        repertoryFlowList.add(initRepertoryFlow(supplierOrder, detail,data,2, storageType));
      });
      // 汇总记录，用作后续的库存流水记录的保存

      //purchaseProductFlows.addAll(purchaseProducts);
      // 初始化贸易中间商订单商品出入库记录（保存扣减的采购单记录）
      detailRecords.addAll(supplierOrderDetailRecordService.initEntityList(detail, purchaseProducts, 1));
    });

    // 保存贸易中间商订单商品出入库记录（保存扣减的采购单记录）
    supplierOrderDetailRecordService.saveBatch(detailRecords);
    //开始处理库存流水日志
    //typ: 2.出库
    //storageType ： 16.贸易中间商发货单（发货） 21.贸易中间商换货单（换货）
    //repertoryFlowService.saveRepertoryFlow(purchaseProductFlows, 2, storageType);
    repertoryFlowService.saveBatch(repertoryFlowList);
    //更新发货单的发货时间
    supplierOrderService.update(Wrappers.lambdaUpdate(SupplierOrder.class)
      .set(SupplierOrder::getDeliveryTime, DateUtils.getNowDate())
      .set(SupplierOrder::getOrderStatus, supplierOrder.getOrderStatus())
      .eq(SupplierOrder::getId, supplierOrder.getId()));
  }

  /**
   * 发货--冲红单据
   *
   * @param records     （贸易中间商）单据商品库存出入库记录数据
   * @param storageType 17.贸易中间商发货单（冲红） 23.贸易中间商换货单（换货冲红）
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void reversalOrderForDelivery(SupplierOrder supplierOrder, List<SupplierOrderDetailRecord> records, Integer storageType) {

    List<RepertoryFlow> repertoryFlowList = new ArrayList<>();
    // 开始处理采购商品
    List<PurchaseProduct> logs = new ArrayList<>();
    Long currentUser = SecurityUtils.getUserId();
    //开始冲红返还
    records.forEach(record -> {
      //找出对应的id的采购商品明细对象数据
      PurchaseProduct purchaseProduct = purchaseProductMapper.selectById(record.getPurchaseProductId());
      if (null != purchaseProduct) {
        //把库存加回去,然后更新.
        Integer productNum = record.getProductNum();
        Integer availableStock = purchaseProduct.getAvailableStock();
        purchaseProduct.setAvailableStock(availableStock + productNum);
        purchaseProductMapper.updateById(purchaseProduct);

        // 查出商品的合同
        SupplierOrderDetail supplierOrderDetail = supplierOrderDetailService.selectSupplierOrderDetailById(record.getOrderDetailId());

        //赋值这些字段只是为了后续日志处理
        purchaseProduct.setPurchaseNumber(supplierOrder.getOrderNo());
        purchaseProduct.setMemberName(supplierOrder.getSupplierName());
        purchaseProduct.setInventoryQuantity(productNum);
        purchaseProduct.setPrice(supplierOrderDetail.getContractPrice());
        purchaseProduct.setBusinessId(supplierOrderDetail.getId());
        purchaseProduct.setCreateBy(currentUser);
        logs.add(purchaseProduct);
      }
      repertoryFlowList.add(initRepertoryFlow(supplierOrder, record.getDetail(),purchaseProduct,2, storageType));
    });

    // 开始处理库存流水日志
    repertoryFlowService.saveBatch(repertoryFlowList);
    // typ: 1.入库
    // storageType ： 16.贸易中间商发货单（发货） 21.贸易中间商换货单（换货）
    //repertoryFlowService.saveRepertoryFlow(logs, 1, storageType);
  }

  /**
   * 退货--新增采购，采购商品明细
   *
   * @param supplierOrder （贸易中间商）单据
   * @param details       （贸易中间商）单据商品
   * @param storageType   18.贸易中间商退货单（退货） 20.贸易中间商换货单（退货）
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void returnSupplierOrder(SupplierOrder supplierOrder, List<SupplierOrderDetail> details, int storageType) {

    // 采购单map集合
    // 因为前端的退货时，每一个商品都可以选择不同的仓库和供应商，
    // 但采购单里面的供应商id，仓库id都是存单个值，所以这里要根据供应商id，仓库id划出多个采购单。
    Map<String, Purchase> purchaseMap = new HashMap<String, Purchase>();
    List<PurchaseProduct> productList = new ArrayList<>();
    List<RepertoryFlow> repertoryFlowList = new ArrayList<>();
    LoginUser user = SecurityUtils.getLoginUser();
    details.forEach(detail -> {
      // 开始获取采购单(先从map中获取，如果获取失败，则判断为新增，先执行保存然后放入map中，后续从缓存中获取，避免重复添加)
      Purchase purchase = getAndSavePurchase(detail, purchaseMap, storageType, user);
      // 初始化当前需保存的（采购单明细）商品库存信息
      PurchaseProduct product = initAndSaveProduct(supplierOrder, detail, purchase);
      //放入purchase对象，以及productList集合中以备后用
      purchase.getPurchaseProductList().add(product);
      productList.add(product);

      repertoryFlowList.add(initRepertoryFlow(supplierOrder, detail,product,1, storageType));
    });

    //开始处理库存流水日志
    repertoryFlowService.saveBatch(repertoryFlowList);
    //typ: 1.入库
    //storageType ： 18.贸易中间商退货单（退货） 20.贸易中间商换货单（退货）
    //repertoryFlowService.saveRepertoryFlow(productList, 1, storageType);

    // 贸易中间商订单商品出入库记录 -- 该记录作用是用户进行冲红操作业务时，方便代码的处理。
    List<SupplierOrderDetailRecord> detailRecords = new ArrayList<>();
    // 构建贸易中间商订单商品出入库记录
    details.forEach(detail -> {
      Purchase purchase = purchaseMap.get(detail.getWarehouseId() + "-" + detail.getSupplierId());
      List<PurchaseProduct> purchaseProducts = null == purchase ? null : purchase.getPurchaseProductList();
      if (!CollectionUtils.isEmpty(productList)) {
        detailRecords.addAll(supplierOrderDetailRecordService.initEntityList(detail, purchaseProducts, 2));
      }
    });
    // 批量保存贸易中间商订单商品出入库记录（保存扣减的采购单记录）
    supplierOrderDetailRecordService.saveBatch(detailRecords);

    //更新退货单的退货时间
    supplierOrderService.update(Wrappers.lambdaUpdate(SupplierOrder.class)
      .set(SupplierOrder::getReturnTime, DateUtils.getNowDate())
      .set(SupplierOrder::getOrderStatus, supplierOrder.getOrderStatus())
      .eq(SupplierOrder::getId, supplierOrder.getId()));
  }

  /**
   * 先从map中获取，如果获取失败，则判断为新增，先执行保存然后放入map中，以备后续使用。
   *
   * @param detail      （贸易中间商）单据商品
   * @param purchaseMap 采购单 - 缓存
   * @param storageType 18.贸易中间商退货单（退货） 20.贸易中间商换货单（退货）
   * @param user        用户
   * @return
   */
  private Purchase getAndSavePurchase(SupplierOrderDetail detail, Map<String, Purchase> purchaseMap, int storageType, LoginUser user) {
    // 先从采购单map集合中获取,获取不到在初始化一个
    String key = detail.getWarehouseId() + "-" + detail.getSupplierId();
    Purchase purchase = purchaseMap.get(key);
    if (null == purchase) {
      purchase = new Purchase();
      purchase.setPurchaseNumber(RedisCode.getCode("RK"));
      purchase.setSupplierId(detail.getSupplierId());
      purchase.setSupplierName(detail.getSupplierName());

      //仓库所属部门
      Warehouse warehouse = iWarehouseService.getById(detail.getWarehouseId());
      if (Objects.isNull(warehouse)) {
        throw new ServiceException("提交失败，仓库已删除，请选择其他仓库，或重新添加。");
      }
      purchase.setWarehouseId(detail.getWarehouseId());
      purchase.setWarehouseName(detail.getWarehouseName());
      purchase.setDeptId(warehouse.getDeptId());

      purchase.setStatus(2);
      purchase.setStorageType(storageType);
      //填充创建人信息
      purchase.setCreateBy(user.getUserId());
      purchase.setCreateTime(DateUtils.getNowDate());
      purchase.setTenantId(user.getTenantId());
      purchase.setPurchaseProductList(new ArrayList<>());
      purchaseMapper.insertPurchase(purchase);
      purchaseMap.put(key, purchase);
    }
    return purchase;
  }

  /**
   * 初始化和保存采购单明细（商品库存）信息
   *
   * @param supplierOrder
   * @param detail        （贸易中间商）单据商品
   * @param purchase      采购单
   * @return
   */
  private PurchaseProduct initAndSaveProduct(SupplierOrder supplierOrder, SupplierOrderDetail detail, Purchase purchase) {
    // 采购单商品
    PurchaseProduct product = new PurchaseProduct();
    product.setPurchaseNumber(supplierOrder.getOrderNo());
    product.setStatus(1);
    product.setBusinessId(detail.getId());
    product.setAvailableStock(detail.getProductNum());
    product.setInventoryQuantity(detail.getProductNum());
    product.setStorageNum(detail.getProductNum());

    product.setSupplierId(detail.getSupplierId());
    product.setSupplierName(detail.getSupplierName());
    product.setWarehouseId(detail.getWarehouseId());
    product.setWarehouseName(detail.getWarehouseName());

    product.setProductId(detail.getProductId());
    product.setProductName(detail.getProductName());
    product.setBatchNumber(detail.getBatchNumber());
    product.setBatchDate(detail.getBatchDate());
    product.setValidity(detail.getValidity());
    product.setManufacturer(detail.getManufacturer());
    product.setRegistrationNumber(detail.getRegistrationNo());

    product.setProductParam(detail.getProductParam());
    product.setBrandName(detail.getBrandName());
    product.setProductCategory(detail.getProductCategory());
    product.setProductEncoded(detail.getProductEncoded());
    product.setUnit(detail.getUnit());
    product.setCostPrice(detail.getContractPrice());
    product.setRemark(detail.getRemark());

    product.setMemberName(supplierOrder.getSupplierName());
    product.setPrice(detail.getContractPrice());


    //填充创建人信息
    product.setPurchaseId(purchase.getId());
    product.setCreateBy(purchase.getCreateBy());
    product.setCreateTime(purchase.getCreateTime());
    product.setTenantId(purchase.getTenantId());
    product.setDeptId(purchase.getDeptId());

    purchaseProductMapper.insertPurchaseProduct(product);
    return product;
  }

  /**
   * 退货--冲红单据
   *
   * @param records     （贸易中间商）单据商品库存出入库记录数据
   * @param storageType 19.贸易中间商退货单（冲红） 22.贸易中间商换货单（退货冲红）
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void reversalOrderForReturn(SupplierOrder supplierOrder, List<SupplierOrderDetailRecord> records, Integer storageType) {

    Long currentUser = SecurityUtils.getUserId();
    Date currentDate = new Date();

    // 开始处理采购商品
    List<PurchaseProduct> logs = new ArrayList<>();
    List<RepertoryFlow> repertoryFlowList = new ArrayList<>();
    records.forEach(record -> {
      // 查出采购商品
      PurchaseProduct purchaseProduct = purchaseProductMapper.selectById(record.getPurchaseProductId());
      if (null != purchaseProduct) {
        if (null == purchaseProduct.getAvailableStock() || null == record.getProductNum()) {
          throw new ServiceException("冲红失败，该商品[" + purchaseProduct.getProdName() + "]的库存数量异常，请联系管理员。");
        }
        //记录中的数据减去当前库存中的可用数量，得出的结果不等于0，则说明有人改了这个数量。这种情况下是不允许冲红的。
        int inventoryQuantity = purchaseProduct.getAvailableStock() - record.getProductNum();
        if (0 != inventoryQuantity) {
          throw new ServiceException("冲红失败，该商品[" + purchaseProduct.getProdName() + "]的库存已被使用。");
        }
        //更新采购商品库存信息。
        LambdaUpdateWrapper<PurchaseProduct> wrapper = Wrappers.lambdaUpdate(PurchaseProduct.class);
        wrapper.set(PurchaseProduct::getStatus, 2);
        wrapper.set(PurchaseProduct::getUpdateBy, currentUser);
        wrapper.set(PurchaseProduct::getUpdateTime, currentDate);
        wrapper.eq(PurchaseProduct::getId, purchaseProduct.getId());
        purchaseProductService.update(wrapper);

        // 查出商品的合同
        SupplierOrderDetail supplierOrderDetail = supplierOrderDetailService.selectSupplierOrderDetailById(record.getOrderDetailId());

        //赋值这些字段只是为了后续日志处理
        purchaseProduct.setPurchaseNumber(supplierOrder.getOrderNo());
        purchaseProduct.setMemberName(supplierOrder.getSupplierName());
        purchaseProduct.setStatus(2);
        purchaseProduct.setInventoryQuantity(purchaseProduct.getAvailableStock());
        purchaseProduct.setPrice(supplierOrderDetail.getContractPrice());
        purchaseProduct.setBusinessId(supplierOrderDetail.getId());
        purchaseProduct.setCreateBy(currentUser);
        logs.add(purchaseProduct);
      }
      repertoryFlowList.add(initRepertoryFlow(supplierOrder, record.getDetail(),purchaseProduct,1, storageType));
    });

    //开始处理采购单：
    Set<Long> ids = records.stream().map(SupplierOrderDetailRecord::getPurchaseId).collect(Collectors.toSet());
    ids.forEach(id -> {
      //获取该采购单下的商品冲红的状况。
      int count = purchaseProductService.count(
        new QueryWrapper<PurchaseProduct>().eq("purchase_id", id).eq("status", 1));
      // 如果存在未冲红的商品，说明是部分冲红，赋值4（部分冲红），反之赋值3（已冲红）
      int stauts = count > 0 ? 4 : 3;
      //更新采购商品库存信息。
      LambdaUpdateWrapper<Purchase> wrapper = Wrappers.lambdaUpdate(Purchase.class);
      wrapper.set(Purchase::getStatus, stauts);
      wrapper.set(Purchase::getUpdateBy, currentUser);
      wrapper.set(Purchase::getUpdateTime, currentDate);
      wrapper.eq(Purchase::getId, id);
      purchaseService.update(wrapper);
    });

    //开始处理库存流水日志
    repertoryFlowService.saveBatch(repertoryFlowList);
    //typ: 2.出库
    //storageType ： 19.贸易中间商退货单（冲红） 22.贸易中间商换货单（退货冲红）
    //repertoryFlowService.saveRepertoryFlow(logs, 1, storageType);
  }

  /**
   * 更新冲红状态
   *
   * @param supplierOrder （贸易中间商）单据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void updateForReversal(SupplierOrder supplierOrder) {
    //更新冲红的状态
    LambdaUpdateWrapper<SupplierOrder> wrapper = Wrappers.lambdaUpdate(SupplierOrder.class);
    wrapper.set(SupplierOrder::getOrderStatus, SupplierOrderStatusEnum.REVERSALED.getStatus());
    wrapper.set(SupplierOrder::getUpdateBy, SecurityUtils.getLoginUser().getUserId());
    wrapper.set(SupplierOrder::getUpdateTime, DateUtils.getNowDate());
    wrapper.eq(SupplierOrder::getId, supplierOrder.getId());
    supplierOrderService.update(wrapper);

    LambdaUpdateWrapper<SupplierOrderDetail> wrapper2 = Wrappers.lambdaUpdate(SupplierOrderDetail.class);
    wrapper2.set(SupplierOrderDetail::getIsRedFlush, 1);
    wrapper2.set(SupplierOrderDetail::getRedFlushTime, DateUtils.getNowDate());
    wrapper2.set(SupplierOrderDetail::getUpdateBy, SecurityUtils.getLoginUser().getUserId());
    wrapper2.set(SupplierOrderDetail::getUpdateTime, DateUtils.getNowDate());
    wrapper2.eq(SupplierOrderDetail::getOrderId, supplierOrder.getId());
    supplierOrderDetailService.update(wrapper2);
  }

  /**
   *
   * @param order 贸易中间商订单
   * @param detail 贸易中间商订单商品
   * @param purchase 库存扣减的流水记录
   * @param flowType 类型（1.入库 2.出库）
   * @param storageType 出库: 16.贸易中间商发货单（发货） 19.贸易中间商退货单（冲红） 21.贸易中间商换货单（换货）22.贸易中间商换货单（退货冲红）
   *                    入库: 17.贸易中间商发货单（冲红）18.贸易中间商退货单（退货）20.贸易中间商换货单（退货） 23.贸易中间商换货单（换货冲红）
   *
   * @return
   */
  private RepertoryFlow initRepertoryFlow(SupplierOrder order, SupplierOrderDetail detail,PurchaseProduct purchase,Integer flowType,Integer storageType) {
    RepertoryFlow repertoryFlow = new RepertoryFlow();
    repertoryFlow.setFlowType(flowType);
    repertoryFlow.setStorageType(storageType);

    // 库存信息
    repertoryFlow.setPurchaseProductId(purchase.getId());
    repertoryFlow.setProductId(purchase.getProductId());
    repertoryFlow.setBusinessId(purchase.getBusinessId());
    repertoryFlow.setProductEncoded(purchase.getProductEncoded());
    repertoryFlow.setProductName(purchase.getProductName());
    repertoryFlow.setProductParameter(purchase.getProductParam());
    repertoryFlow.setBatchNumber(purchase.getBatchNumber());
    repertoryFlow.setValidity(purchase.getValidity());
    repertoryFlow.setSupplierId(purchase.getSupplierId());
    repertoryFlow.setSupplierName(purchase.getSupplierName());
    repertoryFlow.setWarehouseName(purchase.getWarehouseName());

    // 金额信息
    repertoryFlow.setCostPrice(purchase.getCostPrice());
    repertoryFlow.setPrice(purchase.getPrice());

    //判断是否冲红
    boolean flag2 = "17,19,22,23,".contains(repertoryFlow.getStorageType().toString()+",");
    if (flag2) {
      //如果是冲红类型，则数量为负数
      repertoryFlow.setQuantity(-purchase.getInventoryQuantity());
    } else {
      repertoryFlow.setQuantity(purchase.getInventoryQuantity());
    }
    //数量（正数）
    Integer quantity = purchase.getInventoryQuantity();
    // 成本合计 = 成本金额 = 成本单价*数量
    repertoryFlow.setCostAmount(purchase.getCostPrice().multiply(BigDecimal.valueOf(quantity)));

    //判断是否这几种类型，如果是金额则为负数
    boolean flag3 = "17,18,21,22,".contains(repertoryFlow.getStorageType().toString()+",");
    if (flag3) {
      // 金额合计 = 合同单价 * 数量
      repertoryFlow.setAmount(purchase.getPrice().multiply(BigDecimal.valueOf(-quantity)));
    } else {
      // 金额合计 = 合同单价 * 数量
      repertoryFlow.setAmount(purchase.getPrice().multiply(BigDecimal.valueOf(quantity)));
    }

    // 优惠 = 成本合计 - 金额合计
    repertoryFlow.setDiscount(new BigDecimal(0));
    //repertoryFlow.getAmount().subtract(repertoryFlow.getCostAmount())
    // 订单信息
    repertoryFlow.setNumber(order.getOrderNo());
    //repertoryFlow.setMemberId(order.getSupplierId());

    repertoryFlow.setEnterpriseId(order.getSupplierId());
    repertoryFlow.setEnterpriseName(order.getSupplierName());

    repertoryFlow.setMemberName(detail.getPatientName());
    LoginUser loginUser = SecurityUtils.getLoginUser();
    repertoryFlow.setTenantId(loginUser.getTenantId());
    repertoryFlow.setDeptId(loginUser.getDeptId());
    repertoryFlow.setCreateBy(loginUser.getUserId());
    repertoryFlow.setCreateTime(new Date());
    repertoryFlow.setRemark(detail.getRemark());
    return repertoryFlow;
  }
}
